package org.rcy.framework.security.exception;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * @author 吴康桥
 * @Description
 * @date 2022/11/8 17:07
 */


public class FormLoginEntryPoint implements AuthenticationEntryPoint {
	protected final Logger logger = LoggerFactory.getLogger(this.getClass());
	private List<String> domains;
	private String loginFormUrl;

	public FormLoginEntryPoint(String loginFormUrl,List<String> domains) {
		this.loginFormUrl = loginFormUrl;
		this.domains = domains;
	}

	public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
		String redirectUrl = this.replaceRedirectUrl(request, this.loginFormUrl);
		if (this.logger.isDebugEnabled()) {
			this.logger.debug("Redirecting to '" + redirectUrl + "'");
		}

		response.sendRedirect(redirectUrl);
	}

	private String replaceRedirectUrl(HttpServletRequest request, String redirectUrl) {
		String domain = request.getServerName();
		if (!"127.0.0.1".equals(domain) && !"localhost".equals(domain)) {
			String secondaryDomain = domain.substring(domain.indexOf(".") + 1);
			String[] var5 = domains.toArray(new String[domains.size()]);
			int var6 = var5.length;

			for(int var7 = 0; var7 < var6; ++var7) {
				String legalDomain = var5[var7];
				if (redirectUrl.contains(legalDomain)) {
					return redirectUrl.replace(legalDomain, secondaryDomain);
				}
			}

			return redirectUrl;
		} else {
			return redirectUrl;
		}
	}
}
